package com.yjhh.chdataservice.util;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.DoubleRange;

import java.util.regex.Pattern;

/**
 * Created by hlantian on 2017/10/23.
 */
public class DataTools {

    public static String convertToStr(Object object) {
        return object == null ? "" : object.toString();
    }

    public static String convertToStr(Object object, String appendStr) {
        String result = object == null ? "" : object.toString();
        return StringUtils.isNotBlank(result) ? result + appendStr : result;
    }

    public static Double convertToDouble(Object object) {
        String result = object == null ? "" : object.toString();
        return StringUtils.isNotBlank(result) ? Double.parseDouble(result) : 0.0;
    }

    public static Long convertToLone(Object object) {
        String result = object == null ? "" : object.toString();
        return StringUtils.isNotBlank(result) ? Long.parseLong(result) : 0L;
    }

    public static String subDateStr(String appendStr) {
        int index = appendStr.indexOf("T");
        return StringUtils.isNotBlank(appendStr) ? appendStr.substring(0, (index < 0 ? appendStr.length() : index)) : "";
    }

    public static Integer stringToInt(String str) {
        str = StringUtils.isBlank(str) ? "0" : str;
        return StringUtils.isNumeric(str) ? Integer.parseInt(str) : null;
    }

    public static boolean isDouble(String str) {
        if (null == str || "".equals(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
        return pattern.matcher(str).matches();
    }

    /**
     * 替换字符（eg:手机号、身份证号中间部分保密替换）
     *
     * @return
     */
    public static String stringFlagReplace(String resStr, int startRemainNum, int endRemainNum, String replaceChar) {
        if (StringUtils.isBlank(resStr)) {
            return "";
        }
        resStr = resStr.trim();
        int length = resStr.length();
        if (length <= (startRemainNum + endRemainNum)) {
            return resStr;
        }
        return resStr.substring(0, startRemainNum) +
                outCharByCount(resStr.substring(startRemainNum, length - endRemainNum), replaceChar) +
                resStr.substring(length - endRemainNum);
    }

    private static String outCharByCount(String str, String replaceChar) {
        StringBuffer bf = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            bf.append(replaceChar);
        }
        return bf.toString();
    }


    public static Long objToLong(Object obj) {
        String str = XaUtil.isEmpty(obj) ? "0" : obj.toString();
        return StringUtils.isNumeric(str) ? Long.parseLong(str) : null;
    }


}
